"""
数据库连接和会话管理
"""
import os
import logging
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool, StaticPool
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager
from models import Base

logger = logging.getLogger(__name__)

class DatabaseManager:
    """数据库管理器"""
    
    def __init__(self, database_url=None):
        if database_url is None:
            # 默认使用SQLite数据库
            database_url = os.getenv('DATABASE_URL', 'sqlite:///ai_logging_engine.db')
        
        self.database_url = database_url
        engine_kwargs = {
            'echo': False,  # 设置为True可以看到SQL语句
            'pool_pre_ping': True
        }
        # 为SQLite使用NullPool避免文件锁定，便于测试环境删除临时文件
        if database_url.startswith('sqlite'):
            engine_kwargs['connect_args'] = {'check_same_thread': False}
            # 内存数据库需要使用StaticPool共享同一连接，避免表丢失
            if database_url.endswith(':memory:') or database_url == 'sqlite:///:memory:':
                engine_kwargs['poolclass'] = StaticPool
            else:
                # 文件SQLite使用NullPool避免锁
                engine_kwargs['poolclass'] = NullPool
        self.engine = create_engine(database_url, **engine_kwargs)
        self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)
        
        # 简要日志：数据库连接与持久化文件状态
        try:
            logger.info(f"使用数据库: {self.database_url}")
            if self.database_url.startswith('sqlite:///'):
                db_path = self.database_url.replace('sqlite:///', '')
                exists = os.path.exists(db_path)
                logger.info(f"持久化数据文件: {db_path} - {'已存在' if exists else '未找到，将在首次写入时创建'}")
        except Exception:
            # 安全兜底，避免因为日志导致初始化失败
            pass
        
        # 创建表
        self.create_tables()
    
    def create_tables(self):
        """创建数据库表"""
        try:
            Base.metadata.create_all(bind=self.engine)
            logger.info("数据库表创建成功")
        except Exception as e:
            logger.error(f"创建数据库表失败: {e}")
            raise
    
    @contextmanager
    def get_session(self):
        """获取数据库会话的上下文管理器"""
        session = self.SessionLocal()
        try:
            yield session
            session.commit()
        except Exception as e:
            session.rollback()
            logger.error(f"数据库操作失败: {e}")
            raise
        finally:
            session.close()
    
    def get_session_sync(self):
        """获取同步数据库会话（需要手动管理）"""
        return self.SessionLocal()

# 全局数据库管理器实例
db_manager = DatabaseManager()
